package com.wish233.utils;

import cn.hutool.core.lang.Dict;
import cn.hutool.core.util.StrUtil;
import cn.hutool.setting.dialect.Props;
import cn.hutool.setting.yaml.YamlUtil;

/**
 * 配置工具类
 *
 * @author WHH
 */
public class ConfigUtils {

    /**
     * 加载配置对象
     *
     * @param tClass
     * @param prefix
     * @param <T>
     * @return
     */
    public static <T> T loadConfig(Class<T> tClass, String prefix) {
        T t = loadConfigProperties(tClass, prefix, "");
        if (t != null) {
            return t;
        }
        return loadConfigYaml(tClass, prefix, "");
    }

    /**
     * 加载配置对象，支持区分环境
     *
     * @param tClass
     * @param prefix
     * @param environment
     * @param <T>
     * @return
     */
    private static <T> T loadConfigProperties(Class<T> tClass, String prefix, String environment) {
        StringBuilder configFileBuilder = new StringBuilder("application");
        if (StrUtil.isNotBlank(environment)) {
            configFileBuilder.append("-").append(environment);
        }
        configFileBuilder.append(".properties");
        Props props;
        try {
            props = new Props(configFileBuilder.toString());
        } catch (Exception e) {
            return null;
        }
        return props.toBean(tClass, prefix);
    }

    private static <T> T loadConfigYaml(Class<T> tClass, String prefix, String environment) {
        StringBuilder configFileBuilder = new StringBuilder("application");
        if (StrUtil.isNotBlank(environment)) {
            configFileBuilder.append("-").append(environment);
        }
        configFileBuilder.append(".yaml");
        Dict dict = YamlUtil.loadByPath(configFileBuilder.toString(), Dict.class);
        return dict == null ? null : dict.getByPath(prefix, Dict.class).toBean(tClass);
    }
}
